<?php
/**
 * 会员管理
 */
namespace app\admin\controller;
use app\admin\controller\Base;
use app\common\logic\HySuper as HySuperLogic;
use app\common\model\SystemSet as SystemSetModel;
use app\common\model\HuiYuanSupervise;
use app\common\model\SscZaixian;
use app\common\model\SscRizhijl;
use app\common\model\SscUsClass;
use app\common\model\SscTouzhuListSw;
use app\common\model\SscChongzhiList;
use app\common\model\SscTixianList;
use app\common\model\SscDaili;
use think\Db;
use app\common\model\SscUsername;
use think\Exception;
use think\Request;

class Member extends Base
{

    protected $member_model;
	protected $member_logic;
	protected $sysmet;
    protected $sscusername=[];
    protected $ssczaixian=[];
    protected $sscusclass=[];
    protected $sscrizhijilu=[];
    protected $ssctouzhulistsw=[];
    protected $sscchongzhilist=[];
    protected $ssctixianlist=[];
    protected $sscdaili=[];
	public function _initialize(){
		parent::_initialize();
		$this->member_logic = new HySuperLogic();
		$this->sysmet = new SystemSetModel();
		$this->member_model= new HuiYuanSupervise();
        $this->sscusername = new SscUsername();
        $this->ssczaixian = new SscZaixian();
        $this->sscusclass = new SscUsClass();
        $this->sscrizhijilu = new SscRizhijl();
        $this->ssctouzhulistsw = new SscTouzhuListSw();
        $this->sscchongzhilist = new SscChongzhiList();
        $this->ssctixianlist = new SscTixianList();
        $this->sscdaili = new SscDaili();

	}
	/**
	 * 会员列表
	 */
	public function us_list(){
		
		$username=input('ss_sql');
		$this->assign('username',$username);
		$limit=input('get.limit')?input('get.limit'):20;
		$query = $this->member_logic->listHys($limit);
		$start_time = date('Y-m-d',time());
		$end_time = date('Y-m-d',time());
		$us = input('us')?input('us'):input('get.username');
		$this->assign('limit',$limit);
		$this->assign('us',$us);
		$this->assign('query',$query);
		$this->assign('start_time',$start_time);
		$this->assign('end_time',$end_time);
		return $this->fetch();
	}
	public function frozen(){
		$uid = input('uid');
		$beizhu = input('beizhu');
		$status = input('statu');
		$user = Db::name('username')->where('id',$uid)->value('username');
		$data = array('username'=>$user,'frozen'=>$beizhu,'djtime'=>time());
		if(Db::name('frozen')->insert($data)){
			if(Db::name('username')->where('id',$uid)->update(array('open'=>$status))){
				js_tishi('冻结成功','us_list');
			}else{
				alert_back('冻结失败');
			}

		}else{
			alert_back('冻结失败');
		}
	}
	public function dongjie(){
		$user = input('user');

		$query = Db::name('frozen')->where('username',$user)->order('djtime','DESC')->select();
		$this->assign('query',$query);
		return $this->fetch();
	}
	public function dlzhuan(){
		
		$uid = input('uid');
		$user=Db::name('username')->where('id',$uid)->find();
		$this->member_model->caozuorizhi_xieru($user['username'].'转内部会员');
		if(Db::name('username')->where('id',$uid)->update(array('nbzh'=>1))){
			$this->redirect('us_list',['us' => input('us')]);
		}
		
	}

	/**
	 * 查询存取记录
	 * @return \think\mixed
	 */
	public function checkAccessList(){

	    $user = input('get.user');
	    $type = input('get.type');
	    $sum = array();
        if(input('startTime') && input('endTime')){
            $startTime = input('startTime');
            $endTime = input('endTime');
            $time = [$startTime.' 00:00:00',$endTime.' 23:59:59'];
        }else if(empty(input('startTime')) && empty(input('endTime'))){
            $startTime = date('Y-m-d',time()-3600*24*30);
            $endTime = date('Y-m-d',strtotime('+1 day'));
            $time = [date('Y-m-d',time()-3600*24*30).' 00:00:00',date('Y-m-d',strtotime('+1 day')).' 23:59:59'];
        }else{
            $startTime = input('startTime') ? input('startTime') : date('Y-m-d',time()-3600*24*30);
            $endTime = input('endTime') ? input('endTime') : date('Y-m-d',time());
            $time = [$startTime.' 00:00:00',$endTime.' 23:59:59'];
        }
        $where = array('username'=>$user,'zt'=>1);
	    if($type == 'live'){
	        $sum_live = Db::name('chongzhi_list')->where($where)->whereTime('cztime','between',$time)->field('sum(je) as je')->find();
	        $live = Db::name('chongzhi_list')->where($where)->whereTime('cztime','between',$time)->field('je,cztime as time,xxbank as type,bankekh,czadmin,zt')->order('cztime desc')->select();
	        $this->assign('live',$live);
	    }elseif($type == 'take'){
	        $sum_take = Db::name('tixian_list')->where($where)->whereTime('txtime','between',$time)->field('sum(txje) as je')->find();
	        $sum_sgkk = Db::name('sgkk_list')->where('username',$user)->whereTime('kktime','between',$time)->field('sum(kkje) as je')->find();
	        $live = Db::name('tixian_list')->whereTime('txtime','between',$time)->field('txje,txtime as time,czadmin,ifck')->where($where)->order('txtime desc')->select();
	        $made_take = Db::name('sgkk_list')->where('username',$user)->whereTime('kktime','between',$time)->field('kkje as txje,kktime as time,kkliyou,czadmin')->order('kktime desc')->select();
	        $liveAndtake = array_merge($live,$made_take);
	        if(isset($liveAndtake[0])){
	            $live = arraySequence($liveAndtake,'time');
	        }
	    }else{
	        $sum_live = Db::name('chongzhi_list')->where($where)->whereTime('cztime','between',$time)->field('sum(je) as je')->find();
	        $sum_sgkk = Db::name('sgkk_list')->where('username',$user)->whereTime('kktime','between',$time)->field('sum(kkje) as je')->find();
	        $sum_take = Db::name('tixian_list')->where($where)->whereTime('txtime','between',$time)->field('sum(txje) as je')->find();
	        $sum_fs = Db::name('fs_list')->where('username',$user)->whereTime('distribute_time','between',$time)->field('sum(fsje) as je')->find();
	        $sum_caijin = Db::name('caijin_list')->where('username',$user)->whereTime('fstime','between',$time)->field('sum(cjje) as je')->find();
	        $sum_agent = Db::name('agent_balance')->where('agent',$user)->whereTime('add_time','between',$time)->field('sum(balance) as je')->find();

	        $live = Db::name('chongzhi_list')->where($where)->whereTime('cztime','between',$time)->field('je,cztime as time,xxbank as type,bankekh,czadmin,zt')->order('cztime desc')->select();
	        $take = Db::name('tixian_list')->whereTime('txtime','between',$time)->field('txje,txtime as time,czadmin,ifck')->where($where)->order('txtime desc')->select();
	        $made_take = Db::name('sgkk_list')->where('username',$user)->whereTime('kktime','between',$time)->field('kkje as txje,kktime as time,czadmin,kkliyou')->order('kktime desc')->select();
	        $fs = Db::name('fs_list')->where('username',$user)->whereTime('distribute_time','between',$time)->field('fsje as je,distribute_time as time,fsbl,czadmin')->order('distribute_time desc')->select();
	        $caijin = Db::name('caijin_list')->where('username',$user)->whereTime('fstime','between',$time)->field('cjje as je,fstime as time,zzhdid,czadmin')->order('fstime desc')->select();
//			$agent = Db::name('agent_balance')->where('agent',$user)->whereTime('add_time','between',$time)->field('balance as je,add_time as time,higher_agent')->order('add_time desc')->select();
			$agent = Db::name('agent_balance')->group("agent,FROM_UNIXTIME(add_time,'%Y-%m-%d')")->field("FROM_UNIXTIME(add_time,'%Y-%m-%d') as time,sum(balance) as je,agent")->whereTime('add_time','BETWEEN',$time)->where('agent',$user)->order("FROM_UNIXTIME(add_time,'%Y-%m-%d') DESC")->select();

			$liveAndtake = array_merge($live,$take,$made_take,$fs,$caijin,$agent);
	        if(isset($liveAndtake[0])){
	            $live = arraySequence($liveAndtake,'time');
	        }
	    }


	    $sum['live'] = isset($sum_live['je']) ? $sum_live['je'] : 0;
	    $sum['take'] = isset($sum_take['je']) || isset($sum_sgkk['je']) ? $sum_take['je']+$sum_sgkk['je'] : 0;
	    $sum['fs'] = isset($sum_fs['je']) ? $sum_fs['je'] : 0;
	    $sum['caijin'] = isset($sum_caijin['je']) ? $sum_caijin['je'] : 0;
	    $sum['agent'] = isset($sum_agent['je']) ? $sum_agent['je'] : 0;

		$total = count($live);
		$page = input('page',1);
		$limit = 10;
		$pages = ceil($total/$limit);
		$begin = ($page-1)*$limit;
		$live = array_slice($live,$begin,$limit);
		$this->assign('total',$total);
		$this->assign('page',$page);
		$this->assign('pages',$pages);

	    $this->assign('sum',$sum);
	    $this->assign('live',$live);
	    $this->assign('user',$user);
	    $this->assign('type',$type);
	    $this->assign('startTime',$startTime);
	    $this->assign('endTime',$endTime);
	    return $this->fetch('check_access_list');
	}

	public function CheckingRelevantInformation()
	{
		return $this->member_logic->CheckingRelevantInformation(input('get.uid'));
	}
	public function CheckingRelevantInformationDl()
	{
		$query = Db::name('username')->where('id',input('get.uid'))->find();
		return json(array($query['username'],$query['tjm']));
	}
	public function agentUrl(){
		if(input('post.')){
			$data= input('post.');
			if(Db::name('agent_url')->where('id',1)->update($data)){
				$this->member_model->caozuorizhi_xieru('修改代理推广链接');
				js_tishi('成功', 'agentUrl');
			}else{
				alert_back('失败');
			}			
		}else{
			$query = Db::name('agent_url')->where('id',1)->find();
			$this->assign('query',$query);
			return $this->fetch('agent_url');
		}
	}

	public function dl_neweeee(){
		if(input('post.')){
			if(input('fandian')>50){
				alert_back('返点最大值不超过50');
			}
			$data['username'] = input('username');
			$data['password'] = md5(input('password'));
			$data['fandian'] = 0;
			
			$data['tjm'] = $this->code();
			$data['reg_time']=time(); //注册时间
			$data['reg_ip']=get_ip(); //注册ip
			$data['isok']=1;
			$data['tjr']='';
			$data['tjrid']=0;
			$data['je']=0;
			$data['beizhu']='PC';
			$data['khd']=1;
			$query = Db::name('username')->where('username',input('username'))->find();
			if($query['id']){
				js_tishi('账号已存在', 'dl_neweeee');
			}else{

				if(Db::name('username')->insert($data)){
					$this->member_model->caozuorizhi_xieru('添加新代理:'.$data['username']);
					js_tishi('添加成功', 'us_dllist');
				}else{
					alert_back('添加失败');
				}
			}
		}
			return $this->fetch();

	}
	/**
	 * 修改会员信息
	 * @return Ambigous <\think\mixed, string>
	 */
	public function us_xxzl(){

		if(input('get.user')==''){
			$this->sysmet->alertWin('参数不全', "/admin/Member/us_list");
		}else{
			$where = array('username'=>input('get.user'));
			$f = $this->sysmet->dFind('username',$where);
			$bank = $this->sysmet->dLists('bank');
			$class = $this->sysmet->dLists('us_class');
			$this->assign('us',$class);
			$this->assign('bank',$bank);
			$this->assign('f',$f);
			$this->assign('user',input('get.user'));
			$this->assign('user_edit',$this->user_edit);

			return $this->fetch();
		}
	}
	public function xiugainame(){
		if(input('post.')){
			if(Db::name('username')->where('username',input('user'))->update(array('bankren'=>input('post.bankren')))){
				js_tishi('修改成功','xiugainame?user='.input('user'));
			}else{
				alert_back('修改失败');
			}
		}else{
			$user = input('user');
			$f = Db::name('username')->where('username',$user)->find();
			$this->assign('f',$f);
			return $this->fetch();
		}
	}
	public function updateBaseInfo(){
		$where = array('username'=>input('get.user'));
		$post =input('post.');
		$data = array();
		foreach ($post as $k =>$v){
			$j=substr($k, 3);
			if( '未设置'==$v || '无备注'==$v || '未设置银行'==$v || '未设置银行所在省'==$v || '未设置银行所在市'==$v || '未设置开户行'==$v || '未设置开户人'==$v ) $v='';
			if( 'xg_password'==$k && ""==trim($v) ){
				continue;
			}elseif( 'xg_ejmm'==$k && ""==trim($v) ){
				continue;
			}elseif( 'xg_password'==$k || 'xg_ejmm'==$k ){
				$data[$j]=md5($v);
			}elseif( 'xg_mobile'==$k && strpos($v,'****') !== false ){
				continue;
			}elseif( 'xg_qq'==$k && strpos($v,'****') !== false ){
				continue;
			}else{
				$data[$j]=$v;
			}
		}
		if( $this->member_model->SaveUpdate('username', $where, $data) ){
			$this->member_model->caozuorizhi_xieru('修改会员:'.input('get.user').'的用户信息');
			alert_back('修改成功');
		}else {
			alert_back('修改失败');
		}
	}
	public function updateExtInfo(){
		$where = array('username'=>input('get.user'));
		$post =input('post.');
		$data = array();
		foreach ($post as $k =>$v){
			$j=substr($k, 3);
			if('未设置'==$v || '无备注'==$v || '未设置开户人'==$v ) $v='';
			$data[$j]=$v;
		}
		if( $this->member_model->SaveUpdate('username', $where, $data) ){
			$this->member_model->caozuorizhi_xieru('修改会员:'.input('get.user').'的用户信息');
			alert_back('修改成功');
		}else {
			alert_back('修改失败');
		}
	}
	/**
	 * 删除会员
	 */
	public function del_us(){
		$uid=input('param.uid');
		$user=Db::name('username')->where('id',$uid)->find();
		$this->member_model->caozuorizhi_xieru('注销账户:'.$user['username']);
		return $this->member_logic->delMember(input('param.uid'));
	}
	public function del_Dlus(){

		$uid=input('uid');
		$where = array('id'=>input('uid'));
		$tjr = Db::name('username')->where($where)->value('tjr');
		$user=Db::name('username')->where('id',$uid)->find();
		if($tjr){
		  Db::name('username')->where('username',$tjr)->setDec('xjrens');
		}
		$this->member_model->memberDelete('username', $where);
		$this->member_model->caozuorizhi_xieru('注销代理账户:'.$user['username']);
		return $this->sysmet->alertWin('销户成功', "/admin/member/us_dllist");
	}
	/**
	 * 冻结账户
	 */
	public function save_open($uid,$open){
		return $this->member_logic->saveOpne($uid,$open);
	}
	public function nb_save_open($uid,$open){
		return $this->member_logic->nbsaveOpne($uid,$open);
	}
	public function saveDLopen(){
		$uid=input('uid');
		$user=Db::name('username')->where('id',$uid)->find();
		$where = array('id'=>input('uid'));
		$data['open']=input('open');
		$this->member_model->SaveUpdate('username', $where, $data);
		if($data['open']==0){
			$this->member_model->caozuorizhi_xieru('解冻代理账户:'.$user['username']);
		}
		if($data['open']==1){
			$this->member_model->caozuorizhi_xieru('冻结代理账户:'.$user['username']);
		}

		return $this->sysmet->alertWin('操作成功', "/admin/member/us_dllist");
	}
	//--------------代理功能-------------------//

	/**
	 * 代理列表
	 * @return Ambigous <\think\mixed, string>
	 */
	public function dl_list()
	{
		$res = $this->member_logic->dlList(10);
		$this->assign('query',$res['query']);

		$this->assign('daili_renshu',$res['daili_renshu']);
		return $this->fetch();
	}
	public function us_dlnew(){
		if(input('post.')){
			$username = input('username');
			$password = input('password');
			$xxfd = input('fandian');
			$dlcom = input('dl_com');
			$unique_check = Db::name('daili')->where("username='{$username}'")->field('username')->find();

			if($unique_check)
			{
				return $this->error('当前账号已经存在！', "Member/us_new");
			}
			$dlcom = input('dl_com');
			$MYSQL_ZIDUAN = array(
					'username' => $username,
					'password' => $password,
					'xxfd' => $xxfd,
					'dl_com'=>$dlcom,
					'tzm'=>''
			);

			$member_add  = $this->sscdaili->Dailiyixia($MYSQL_ZIDUAN);

			if($member_add)
			{
				$this->member_model->caozuorizhi_xieru('新增合作商:'.$username);
				return js_tishi('添加成功', "/admin/Member/dl_list");
			}else
			{
				return $this->error('添加失败', "Member/us_new");
			}
		}
		return $this->fetch();
	}

	/**
	 ** 单个代理查询
	 ** @param $dluser[string 代理名字]
	 ** return fetch
	**/
	public function dl_zh()
	{
		$dluser = input('DLUSER');
		if(!$dluser)
		{
			return $this->error('查询参数缺失','Member/dl_list');
		}
		//查询代理账号信息
		$dl_zl = Db::name('daili')->where('username',$dluser)->find();

		$this->assign('dl_zl',$dl_zl);
		return $this->fetch();
	}

	/**
	 ** 修改代理信息
	 ** @param $xg_username
	 ** @param $xg_name
	 ** @param $xg_password
	 ** @param $xg_beizhu
	 ** @param $xg_mobile
	 ** @param $xg_com
	 ** return fetch
	**/
	public function dl_zh_modify()
	{
		foreach(input('post.') as $k=>$v){
			${$k} = $v;
		}
		//1.先查询是否有修改权限【auth已认证】
		//2.先判断参数
		if(!$xg_username  || !$xg_name || !$xg_beizhu || !$xg_mobile || !$xg_com)
		{
			return $this->error('修改参数缺失',"Member/dl_zh?DLUSER={$xg_username}");
		}

		//2.有提交修改数据的情况下,执行修改
		$update_data = array(
			'dl_name'=> $xg_name,
			'beizhu'=> $xg_beizhu,
			'dl_com'=> $xg_com,
			'mobile'=> $xg_mobile,
		);

		if($xg_password!="")
		{
			$xg_password = md5($xg_password);
			$update_data['password']=$xg_password;
		}

		//Db::startTrans();

		//try{
			//1.修改代理信息
			$this->sscdaili->DailiModify($update_data,$xg_username);
			//2.记录操作日志
			$jilu_data = array(
				'rz_class' => 1,
				'rz_test' => admin_text(34).$xg_username,
				'rz_time' => time(),
				'rz_ip' => get_ip(),
				'rz_user' => session('user.nickname')
			);
			$this->sscrizhijilu->RizhiInsert($jilu_data);
		  //  Db::commit();
		  	$this->member_model->caozuorizhi_xieru('修改合作商:'.$xg_name.'的资料信息');
		    return $this->success('修改成功',"Member/dl_list");
		//} catch (\Exception $e) {
		//    Db::rollback();
		//    return $this->error('修改失败',"Member/dl_zh?DLUSER={$xg_username}");
		//}
	}


	/**
	 ** 代理下线列表
	 ** @param $DLUSER[string 推荐人]
	**/
	public function dl_xx_list()
	{
		$DLUSER = input('get.DLUSER');
		//1.验证参数是否完整
		if(!$DLUSER)
		{
			return $this->error('查询参数缺失','Member/dl_list?id=51&cid=49');
		}
		//2.执行查询
		$res = $this->member_logic->dlListSingle($limit=10,$dluser=$DLUSER);
		$this->assign('query',$res['query']);
		$this->assign('daili_renshu',$res['daili_renshu']);
		$this->assign('dluser',$DLUSER);
		$this->assign('user_ss',input('post.user_ss'));
		$this->assign('date_ss',input('post.date_ss'));
		return $this->fetch();

	}

	//--------------代理功能-------------------//

    /**
     * 内部账户
     * @return Ambigous <\think\mixed, string>
     */
	public function nbus_list(){
        $USER_SS=input('post.USER_SS');
        $where=array(
            'nbzh'=>1
        );
        $order='id desc';
        $username=input('post.username')?input('post.username'):input('get.username');
        $limit=input('get.limit')?input('get.limit'):20;
      
        $ZCOUNTs = Db::name('username')->where($where)->where("username", "like","%{$username}%")->order($order)->paginate($limit);
        $this->assign('limit',$limit);
        $this->assign('username',$username);
        $this->assign('DL_LIST',$ZCOUNTs);
		return $this->fetch();
	}
    /**
     * 内部账户改
     * @return Ambigous <\think\mixed, string>
     */
    public function nbus_zl(){
        $USER_SS=input('DLUSER');
       	$query = Db::name('username')->where('username',$USER_SS)->find();
        $this->assign('DLZL',$query);
        return $this->fetch();
    }
    /**
     * 内部账户删除
     * @return Ambigous <\think\mixed, string>
     */
    public function del(){
        $DLUSER=input('DLUSER');
        $where = array(
            'username'=>$DLUSER
        );
        $shanchu = $this->sscusername->Shan($where);
        if($shanchu){
        	$this->member_model->caozuorizhi_xieru('删除内部账户:'.$DLUSER);
            return $this->success('删除成功','Member/nbus_list');
        }else{
            return $this->success('删除失败','Member/nbus_list');
        }
    }
    /**
     * 内部账户一键清理
     * 删除用户 【投注/充值/提现记录】
     * @return Ambigous <\think\mixed, string>
     */
    public function qinglizhanghao(){
        $DLUSER=input('DLUSER');
        if($DLUSER==""){

            $where = array(
                'nbzh'=>1
            );

            Db::startTrans();
            $reone=$this->sscusername->Shan($where);
            $retwo=$this->ssctouzhulistsw->TouzhuJilu($where);
            $rethree=$this->sscchongzhilist->ChongzhiShan($where);
            $refour=$this->ssctixianlist->TixianShan($where);
            if($reone & $retwo & $rethree & $refour){
            	Db::commit();
            	$this->member_model->caozuorizhi_xieru('一键删除内部账号');
                return $this->success('删除内部账户成功','Member/nbus_list');
            }else{
            	Db::rollback();
                return $this->success('删除内部账户失败','Member/nbus_list');
            }


        }else{
            $where = array(
                'nbzh'=>'1',
                'username'=>$DLUSER,
            );
            Db::startTrans();
            $refive=$this->sscusername->Shan($where);
            $resix=$this->ssctouzhulistsw->TouzhuJilu($where);
            $reseven=$this->sscchongzhilist->ChongzhiShan($where);
            $reeight=$this->ssctixianlist->TixianShan($where);
            if($refive){
            	Db::commit();
            	$this->member_model->caozuorizhi_xieru('删除内部账号:'.$DLUSER);
                return $this->success('删除内部账户成功','Member/nbus_list');
            }else{
            	Db::rollback();
                return $this->error('删除内部账户失败');
            }
        }

    }
    /**
     * 内部账户清理以及一键清理
     * @return Ambigous <\think\mixed, string>
     */
    public function qingli(){
        $DLUSER=input('DLUSER');
        if($DLUSER==''){
            $where['nbzh']=1;
            Db::startTrans();
            $reone=$this->ssctouzhulistsw->TouzhuJilu($where);
            $retwo=$this->sscchongzhilist->ChongzhiShan($where);
            $rethree=$this->ssctixianlist->TixianShan($where);
            if($reone & $retwo & $rethree){
            	Db::commit();
            	$this->member_model->caozuorizhi_xieru('一键清空内部账号');
                return $this->success('内部账户清理成功','Member/nbus_list');
            }else{
            	Db::rollback();
                return $this->error('内部账户清理失败');
            }

        }else{

            $where=array(
                'username'=>$DLUSER,
                'nbzh'=>1,
            );
            Db::startTrans();
            $refive=$this->ssctouzhulistsw->TouzhuJilu($where);
            $resix=$this->sscchongzhilist->ChongzhiShan($where);
            $reseven=$this->ssctixianlist->TixianShan($where);

            if($refive & $resix & $reseven){
            	Db::commit();
            	$this->member_model->caozuorizhi_xieru('清理内部账号:'.$XG_USERNAME.'的所有记录');
                return $this->success('内部账户清理成功','Member/nbus_list');
            }else{
            	Db::rollback();
                return $this->error('内部账户清理,暂无数据');
            }

        }


    }
    /**
     * 内部账户改
     * @return Ambigous <\think\mixed, string>
     */
    public function upgai(){
        $XG_USERNAME=input('post.XG_USERNAME');
        $XG_PASSWORD=input('post.XG_PASSWORD','');
        $XG_BEIZHU=input('post.XG_BEIZHU','');
        if($XG_PASSWORD==''){
            $where = array(
                'username'=>$XG_USERNAME
            );
            $setzhiduan=array(
                'beizhu'=>$XG_BEIZHU
            );
            $gaibian = $this->sscusername->Xiugai($where,$setzhiduan);
            if($gaibian){
            	$this->member_model->caozuorizhi_xieru('修改内部账号:'.$XG_USERNAME);
                return $this->success('修改成功','Member/nbus_list');
            }else{
                return $this->success('修改失败','Member/nbus_zl?DLUSER='.$XG_USERNAME);
            }
        }else{
            $where = array(
                'username'=>$XG_USERNAME
            );
            $setzhiduan=array(
                'password'=>md5($XG_PASSWORD),
                'beizhu'=>$XG_BEIZHU
            );
            $gaibian = $this->sscusername->Xiugai($where,$setzhiduan);
        }
        if($gaibian){
        	$this->member_model->caozuorizhi_xieru('修改内部账号:'.$XG_USERNAME);
            return $this->success('修改成功','Member/nbus_list');
        }else{
            return $this->success('修改失败','Member/nbus_zl?DLUSER='.$XG_USERNAME);
        }

    }
    /**
     * 试玩账号
     * @return Ambigous <\think\mixed, string>
     */
	public function swus_list(){
        $fileds = "*";
        $where['swzh'] = 1;
        $order='id desc';
        
        $username=input('post.username')?input('post.username'):input('get.username');
        $limit=input('get.limit')?input('get.limit'):20;
      
        $czlisu="?id=".input('id')."&cid=".input('cid');

        $listareas=Db::name('username')->where($where)->where("username", "like","%{$username}%")->order('id desc')->paginate($limit);
        //分页显示输出
        $page=$listareas->render();
        $this->assign('limit',$limit);
        $this->assign('username',$username);
        $this->assign('listarea',$listareas);
		$this->assign('id',input('id'));
		$this->assign('cid',input('cid'));
		return $this->fetch();
	}
    /**
     * 一键清理试玩账号
     * @return Ambigous <\think\mixed, string>
     */
    public function swus_qingli(){
        $where = array(
            'swzh'=>'1',

        );
        $result=$this->sscusername->Shan($where);
        if($result){
        	$this->member_model->caozuorizhi_xieru('一键清理全部试玩账号');
            return $this->success('清理成功',"Member/swus_list?id=".input('id')."&cid=".input('cid'));
        }else{
            return $this->error('清理失败',"Member/swus_list?id=".input('id')."&cid=".input('cid'));
        }
    }

    /**
     * 在线列表
     * @return Ambigous <\think\mixed, string>
     * @param $USER_SS[string 用户名称]
     * return fetch
     */
    public function zxus_list()
	{
//	    //清除失效在线用户信息
//	    $limit=input('get.limit')?input('get.limit'):20;
//	    $this->assign('limit',$limit);
//
//	    $time = time() - 3600;
//	    $is_del = Db::name('zaixian')->where("login_time + time_lingt<{$time}")->column('id');
//	    if($is_del) {
//	        $ids = join(',',$is_del);
//	        Db::name('zaixian')->where('id','IN',$ids)->delete();
//	    }
//
//	    $key_user = input('key_user');
//	    $where = array();
//	    if($key_user) {
//	        $where = ['u.username'=>['LIKE',"%{$key_user}%"]];
//	    }
//
//   	    $zaixian_list = Db::name('username')->alias('u')
//   	    ->field('u.id,u.username,zc.class_name,u.je,zx.login_ip,zx.login_url,u.reg_time,zx.time_lingt,zx.login_time,u.tjr,u.beizhu,u.khd,u.swzh,u.nbzh')
//		->join('__ZAIXIAN__ zx','u.username = zx.username')
//		->join('__US_CLASS__ zc','zc.id = u.us_class')
//		->where($where)
//		->paginate($limit)
//		->each(function($zaixian_single, $key) {
//				$zaixian_single['reg_time'] = date('Y-m-d H:i:s',$zaixian_single['reg_time']);
//		 		$zaixian_single['login_time'] = date('Y-m-d H:i:s',$zaixian_single['login_time']);
//		 		$zaixian_single['time_lingt'] = $zaixian_single['time_lingt']/60;
//				$zaixian_single['time_lingt'] = floor($zaixian_single['time_lingt']*100)/100;
//				$zaixian_single['time_lingt'] = $zaixian_single['time_lingt'].'分钟';
//
//				if(!$zaixian_single['beizhu']) $zaixian_single['beizhu'] = '/ 无备注 /';
//				return $zaixian_single;
//		});
//
//        $this->assign('key_user',$key_user);
//        $this->assign('zaixian_list',$zaixian_list);
//		return $this->fetch();
		//清除失效在线用户信息

	    $limit=input('limit',20);

	    $key_user = input('key_user','');
	    $where = [];
	    if($key_user) {
	        $where = ['u.username'=>['LIKE',"%{$key_user}%"]];
	    }

   	    $zaixian_list = Db::name('username')->alias('u')
		->join('__US_CLASS__ zc','zc.id = u.us_class')
		->field('u.id,u.username,zc.class_name,u.je,u.reg_time,u.login_ip,u.tjr,u.beizhu,u.khd,u.swzh,u.nbzh,u.current_from,u.current_time')
		->where($where)->where(['u.current_from'=>['>',0]])
		->paginate($limit)
		->each(function($v) {

			$v['login_time'] = date('Y-m-d H:i:s',$v['current_time']);
			$diff_time = time()-$v['current_time'];
			$v['time_lingt'] = intval($diff_time / 60) .'分钟';
			return $v;
		});
        $this->assign('key_user',$key_user);
        $this->assign('zaixian_list',$zaixian_list);
		$this->assign('limit',$limit);

		return $this->fetch();

	}

    /**
     * 在线列表踢出
     * @return Ambigous <\think\mixed, string>
     */
    public function  GoOut(){
        $usern=input('get.usern');
        if(!$usern)
        {
        	return $this->success('参数缺失','Member/zxus_list');
        }
        $where=array(
            'username'=>$usern
        );
        $setzhiduan=array(
            'login_key'=>'gun',
			'current_from'=>0
        );
        $this->sscusername->Xiugai($where,$setzhiduan);
        $this->ssczaixian->ShanZaixian($where);
        $this->member_model->caozuorizhi_xieru('提出账号:'.$usern);
        return $this->success('踢出成功','Member/zxus_list');

    }
    /**
     * 会员等级
     * @return Ambigous <\think\mixed, string>
     */
	public function usclass_list(){
        $order = 'id desc';
        $limit = '';
        $DL_LIST = Db::name('us_class')->order('czl asc')->select();
        foreach ($DL_LIST as &$i){
        	$i['czl'] = floor($i['czl']);
        	$i['xml'] = floor($i['xml']);
        	$i['mearmoney'] = floor($i['mearmoney']);
        	$i['zxtzxd'] = floor($i['zxtzxd']);
            $i['count'] = Db::name('username')->where('us_class',$i['id'])->where('nbzh',0)->where('swzh',0)->field('id')->count();
        }
        $this->assign('DL_LISTs',$DL_LIST[0]);
        $this->assign('DL_LIST',$DL_LIST);
		return $this->fetch();
	}
    /**
     * 新增会员等级
     * @return Ambigous <\think\mixed, string>
     */
    public function usclass_tj(){

        return $this->fetch();
    }
    /**
     * 新增会员等级
     * @return Ambigous <\think\mixed, string>
     */
    public function tianjia(){
        $class_name = input('post.class_name','');
		$fsbl = input('post.fsbl',0.00);
		$dividend = input('post.dividend',0.00);
		$czzsbl = input('post.czzsbl',0);
        $czl = input('post.czl',0);
        $xml = input('post.xml',0);
        if($class_name){
            $zhiduan=array(
                'class_name'=>$class_name,
                'fsbl'=>$fsbl,
                'dividend'=>$dividend,
                'czzsbl'=>$czzsbl,
            	'czl'=>$czl,
            	'xml'=>$xml,
				'mearmoney'=>input('post.mearmoney',0.00),
				'zxtzxd'=>input('post.zxtzxd',0.00),
//            	'zdtzxd'=>input('post.zdtzxd')
            );
            $re=$this->sscusclass->HuiYuanTian($zhiduan);
            if($re){
            	$this->member_model->caozuorizhi_xieru('新增会员等级:'.$class_name);
                js_tishi('添加成功','usclass_list');
            }else{
                alert_back('添加失败');
            }
        }else{
            alert_back('不能空添加');
        }

    }
    /**
     * 会员等级删除
     * @return Ambigous <\think\mixed, string>
     */
    public function querenshanchu(){
        $USERN=input('get.USERN');
        $where=array(
            'id'=>$USERN
        );
        $result=Db::name('us_class')->where($where)->find();
        $re=$this->sscusclass->HuiYuanDel($where);
        if($re){
        	$this->member_model->caozuorizhi_xieru('删除会员等级'.$result['class_name']);
            js_tishi('删除成功','usclass_list');
        }else{
            alert_back('删除失败');
        }


    }
    /**
     * 会员等级修改
     * @return Ambigous <\think\mixed, string>
     */
    public function hyxiugai(){
        $DLUSER  =input('DLUSER') ? input('DLUSER') : alert_back('参数缺失');
        $fileds = '*';
        $where=array(
            'id'=>$DLUSER
        );
        $DL_LIST = $this->sscusclass->HuiYuan($fileds,$where,'','');
        $this->assign('DL_LIST',$DL_LIST[0]);
        return $this->fetch();

    }
    /**
     * 会员等级修改确认
     * @return Ambigous <\think\mixed, string>
     */
    public function xiugaiqueren(){
        $class_id = input('post.class_id') ? input('post.class_id') : alert_back('参数缺失');
        $class_name = input('post.class_name','');
        $dividend = input('post.dividend',0.00);
        $czzsbl = input('post.czzsbl',0);
        $fsbl = input('post.fsbl',0.00);
        $czl = input('post.czl',0);
        $xml = input('post.xml',0);
        $fileds = '*';
        $where = array(
            'id'=>$class_id
        );
        $DL_LISTs = $this->sscusclass->HuiYuan($fileds,$where,'','');
        $class_names = $DL_LISTs[0]['class_name'];
        $czzsbls = $DL_LISTs[0]['czzsbl'];
        $where = array(
            'id'=>$class_id
        );
        $setzhiduan=array(
            'class_name'=>$class_name,
            'fsbl'=>$fsbl,
            'czzsbl'=>$czzsbl,
        	'czl'=>$czl,
        	'xml'=>$xml,
        	'dividend'=>$dividend,
			'mearmoney'=>input('post.mearmoney',0.00),
			'zxtzxd'=>input('post.zxtzxd',0.00),
//			'zdtzxd'=>input('post.zdtzxd')
        );
        $re=$this->sscusclass->HuiYuangai($where,$setzhiduan);
        if($re){
            $where=array(
                'id'=>$class_id
            );
            $DL_LISTses = $this->sscusclass->HuiYuan($fileds,$where,'','');
            $class_nameses=$DL_LISTses[0]['class_name'];
            $czzsblses=$DL_LISTses[0]['czzsbl'];
            $jilu_data = array(
                'rz_class' => 1,
                'rz_test' => admin_text(34).'把原来会员'.$class_names.'等级修改为'.$class_nameses.'<br/>'.'把充值额外赠送百分比'.$czzsbls.'修改为'.$czzsblses,
                'rz_time' => time(),
                'rz_ip' => get_ip(),
                'rz_user' => session('user.nickname')
            );
            $this->sscrizhijilu->RizhiInsert($jilu_data);
            js_tishi('修改成功','usclass_list');
        }else{
            alert_back('修改失败');
        }

    }
    /**
     * 新增会员
     * @return Ambigous <\think\mixed, string>
     */
	public function us_new()
	{
		$this->assign('id',input('id'));
		$this->assign('cid',input('cid'));
		return $this->fetch();
	}


    /**
     * 新增会员
     * @return Ambigous <\think\mixed, string>
     */
    public  function  huiyuannew()
    {
        $NEW_USERNAME=input('post.NEW_USERNAME'); //用户名
        $NEW_PASSWORD=input('post.NEW_PASSWORD'); //密码
        $NEW_USCLASS=4;  //会员类型
        $NTIEM=time(); //注册时间
        $LOGIN_IP=get_ip(); //注册ip
        $FUKUDUAN='1'; //1为电脑端  2为手机端
        $LOGIN_KEY=suiji_zifu(15);
        if($NEW_USCLASS==1){
        	$isok=1;
        }else{
        	$isok=0;
        }
        //1.判断是否缺少参数
        if($NEW_USERNAME=="" || $NEW_PASSWORD=="" || $NEW_USCLASS=="")
        {
			return $this->error('参数缺失', "Member/us_new");
        }
		if(strlen($NEW_PASSWORD)<6 || strlen($NEW_PASSWORD)>16){
			alert_back('密码必须是6-16位字母或者数字');
		}
        $NEW_PASSWORD = md5($NEW_PASSWORD);


        $unique_check = Db::name('username')->where("username='{$NEW_USERNAME}'")->field('username')->find();

        if($unique_check)
    	{
			return $this->error('当前账号已经存在！', "Member/us_new");
    	}

    	$MYSQL_ZIDUAN = array(
            'username' => $NEW_USERNAME,
            'password' => $NEW_PASSWORD,
            'je' => '0',
    		'fandian'=>0,
    		
    		'tjm'=>$this->code(),
            'reg_time' => $NTIEM,
            'reg_ip' => get_ip(),
            'us_class' => '4',
            'khd' => '1',
        );

        $NEW_USCLASS == '4' && $MYSQL_ZIDUAN['nbzh'] = '1';

        $member_add = $this->sscusername->Jiayixia($MYSQL_ZIDUAN);
        $us = Db::name('username')->where('username',$NEW_USERNAME)->value('id');
       /* $id = $us;
    	if(strlen($us)==1){$id='0000000'.$us;}
		if(strlen($us)==2){$id='000000'.$us;}
		if(strlen($us)==3){$id='00000'.$us;}
		if(strlen($us)==4){$id='0000'.$us;}
		if(strlen($us)==5){$id='000'.$us;}
		if(strlen($us)==6){$id='00'.$us;}
		if(strlen($us)==7){$id='0'.$us;}
		$data = array('tjm'=>$id);
		Db::name('username')->where('id',$us)->update($data);*/
        if($member_add)
        {
        	$this->member_model->caozuorizhi_xieru('新增会员:'.$NEW_USERNAME);
        	return js_tishi('添加成功', "/admin/Member/us_new");
        }else
        {
        	alert_back('添加失败');
        }
    }
	function code(){
		$code=rand('00000000','99999999');
		/* for($i=1;$i<=2;$i++){
			$code .= chr(rand(97,122));
		}
		for($i=1;$i<=1;$i++){
			$code .= chr(rand(65,90));
		}
		for($i=1;$i<=1;$i++){
			$code .= chr(rand(97,122));
		}
		for($i=1;$i<=4;$i++){
			$code .= chr(rand(65,90));
		}
		for($i=1;$i<=2;$i++){
			$code .= chr(rand(97,122));
		}
		for($i=1;$i<=3;$i++){
			$code .= chr(rand(65,90));
		} */
		if($code != ''){
			$c = Db::name('username')->where('tjm',$code)->find();
			if($c){
				$this->code();
			}
		}
		return $code;
	}

    /**
     * 登陆日志
     * @return Ambigous <\think\mixed, string>
     */
	public function jc_all(){
		
		$limit=input('get.limit')?input('get.limit'):20;
	    $where = array();
        $us_sql=input('us_sql') ? input('us_sql') : input('get.username');
        $ip_sql=input('ip_sql') ? input('ip_sql') : input('get.ip');
        if(input('sDate1') && input('sDate2')){
            $where['rz_time'] = array('between',[strtotime(input('get.sDate1')),strtotime(input('get.sDate2'))]);
        }
        $where['rz_class'] = 2;
        $order = 'rz_time desc';
        if ($us_sql || $ip_sql) {

            if($us_sql) {
                $where['rz_user'] = ['like',"%{$us_sql}%"];
            }
            if($ip_sql) {
                $where['rz_ip'] = ['like',"%{$ip_sql}%"];
            }

            $ZCOUNT = $this->sscrizhijilu->Rizhi($where, $order,$limit);
        } else {
            $ZCOUNT = $this->sscrizhijilu->Rizhi($where, $order,$limit);
        }
        $this->assign('limit',$limit);
        $this->assign('listes',$ZCOUNT);
        $this->assign('us_sql',$us_sql);
        $this->assign('ip_sql',$ip_sql);
	    return $this->fetch();
	}
	public function us_dllist()
	{
		$limit=input('get.limit')?input('get.limit'):20;
		$this->assign("limit",$limit);
		$query = $this->member_logic->dlListHys($limit);
		$m = Db::name('username')->where(['swzh'=>['<>',1]])->select();
		foreach ($query as &$item){
			$at = array('czzje'=>0,'tzzje'=>0,'txzje'=>0);
			$this->sztrw($m,$item['uid'],$at);
			$item['tdczzje'] = empty($at['czzje']) ? 0 : $at['czzje'];
			$item['tdtzzje'] = empty($at['tzzje']) ? 0 : $at['tzzje'];
			$item['tdtxzje'] = empty($at['txzje']) ? 0 : $at['txzje'];
			$balance = Db::name('agent_balance')->where(['agent'=>$item['username'],'status'=>1])->value('SUM(balance)');
			$item['dlyj'] = $balance;
		}
		$username=input('ss_sql');
		$us = input('us');
		$time1=input('post.sDate1')?input('post.sDate1'):input('get.time1');
		$time2=input('post.sDate2')?input('post.sDate2'):input('get.time2');
		if($time1 || $time2){
			$time1=$time1?$time1."00:00:00":date('Y-m-d',time())." 00:00:00";
			$time2=$time2?$time2."23:59:59":date('Y-m-d',time())." 23:59:59";
		}
		$this->assign('username',$username);
		$this->assign('time1',$time1);
		$this->assign('time2',$time2);
		$this->assign('us',$us);
		$this->assign('query',$query);
		return $this->fetch();
	}
	function sztrw($arr,$pid,&$at){

		if(is_array($arr)){
			foreach ($arr as $v){

				if($v['tjrid']==$pid){

					$at['czzje'] += $v['czzje'];
					$at['tzzje'] += $v['tzzje'];
					$at['txzje'] += $v['txzje'];

					$this->sztrw($arr,$v['id'],$at);
				}
			}
		}

	}
	/**
	 * 层级关系图
	 */
	public function hierarchyDiagram(){

		$uid = input('yhid',0);
		$time=input('time','');
		$user = Db::name("username")->field("id,username,dml,zcjje,czzje,tzzje,txzje,dl,tjrid,je")->find($uid);
		$user['level'] = 0;
		$list = self::hierarchyTree($uid,1);
		array_unshift($list,$user);
		
		if(!empty($time)){
			$dlyj_arrt = Db::name('agent_balance')->whereTime('add_time',$time)->group('agent')->column('SUM(balance)','agent');
			$zjzje_attr = Db::name('touzhu_list_ok')->whereTime('tz_time',$time)->group("username")->column('SUM(zjje)','username');
			$tzzje_attr = Db::name('touzhu_list_ok')->whereTime('tz_time',$time)->group("username")->column('SUM(tzje)','username');
			$cj_arrt = Db::name('caijin_list')->whereTime('fstime',$time)->group("username")->column('SUM(cjje)','username');
			$cz_arrt = Db::name('chongzhi_list')->whereTime('cztime',$time)->where('zt',1)->group("username")->column('SUM(je)','username');
			$tx_arrt = Db::name('tixian_list')->whereTime('txtime',$time)->where('zt',1)->group("username")->column('SUM(txje)','username');
		}else{
			$dlyj_arrt = Db::name('agent_balance')->group('agent')->column('SUM(balance)','agent');
			$zjzje_attr = Db::name('touzhu_list_ok')->group("username")->column('SUM(zjje)','username');
			$tzzje_attr = Db::name('touzhu_list_ok')->group("username")->column('SUM(tzje)','username');
			$cj_arrt = Db::name('caijin_list')->group("username")->column('SUM(cjje)','username');
			$cz_arrt = Db::name('chongzhi_list')->where('zt',1)->group("username")->column('SUM(je)','username');
			$tx_arrt = Db::name('tixian_list')->where('zt',1)->group("username")->column('SUM(txje)','username');
		}
		$team = ['username'=>'团队小计','je'=>0,'dlyj'=>0,'dml'=>0,'zjzje'=>0,'zcjje'=>0,'czzje'=>0,'tzzje'=>0,'txzje'=>0,'level'=>-1];
		$total = ['username'=>'总计','je'=>0,'dlyj'=>0,'dml'=>0,'zjzje'=>0,'zcjje'=>0,'czzje'=>0,'tzzje'=>0,'txzje'=>0,'level'=>-1];
		foreach($list as $k=>&$v){
			$v['zjzje'] = isset($zjzje_attr[$v['username']]) ? $zjzje_attr[$v['username']] : 0;
			$v['dlyj'] = isset($dlyj_arrt[$v['username']]) ? $dlyj_arrt[$v['username']]:0;
			$v['tzzje'] = isset($tzzje_attr[$v['username']]) ? $tzzje_attr[$v['username']]:0;
			$v['zcjje'] = isset($cj_arrt[$v['username']]) ? $cj_arrt[$v['username']]:0;
			$v['czzje'] = isset($cz_arrt[$v['username']]) ? $cz_arrt[$v['username']]:0;
			$v['txzje'] = isset($tx_arrt[$v['username']]) ? $tx_arrt[$v['username']]:0;
			$total['je'] += $v['je'];
			$total['dlyj'] += $v['dlyj'];
			$total['dml'] += $v['dml'];
			$total['zjzje'] += $v['zjzje'];
			$total['zcjje'] += $v['zcjje'];
			$total['czzje'] += $v['czzje'];
			$total['tzzje'] += $v['tzzje'];
			$total['txzje'] += $v['txzje'];
		}
		unset($v);
		$team['je'] = sprintf("%.2f",$total['je'] - $list[0]['je']);
		$team['dlyj'] = sprintf("%.2f",$total['dlyj'] - $list[0]['dlyj']);
		$team['dml'] = sprintf("%.2f",$total['dml'] - $list[0]['dml']);
		$team['zjzje'] = sprintf("%.2f",$total['zjzje'] - $list[0]['zjzje']);
		$team['zcjje'] = sprintf("%.2f",$total['zcjje'] - $list[0]['zcjje']);
		$team['czzje'] = sprintf("%.2f",$total['czzje'] - $list[0]['czzje']);
		$team['tzzje'] = sprintf("%.2f",$total['tzzje'] - $list[0]['tzzje']);
		$team['txzje'] = sprintf("%.2f",$total['txzje'] - $list[0]['txzje']);
		array_push($list,$team);
		array_push($list,$total);
		$this->assign('uid',$uid);
		$this->assign('time',$time);
		$this->assign('list',$list);
		return $this->fetch('cjgxt');
	}
	static function hierarchyTree( $uid,$level ){
		static $ret = [];
		$list = Db::name("username")->where(['tjrid'=>$uid])->field("id,username,dml,zcjje,czzje,tzzje,txzje,dl,tjrid,je")->select();
		$idAttr[] = $uid;
		foreach($list as $v){
			$v["level"] = $level;
			$ret[] = $v;
			if($level<3){
				self::hierarchyTree($v['id'],$level+1);
			}
		}
		return $ret;
	}
	public function hierarchyDiagram_old(){
		$yhid = input('yhid');
		$m = Db::name('username')->where(['nbzh'=>['<>',1],'swzh'=>['<>',1]])->select();

		foreach ($m as &$va){
			$va['dlyj'] = Db::name('agent_balance')->where('agent',$va['username'])->value('SUM(balance)')?Db::name('agent_balance')->where('agent',$va['username'])->value('SUM(balance)'):'0';
			$va['zjzje'] = Db::name('touzhu_list_ok')->where('username',$va['username'])->value('SUM(zjje)')?Db::name('touzhu_list_ok')->where('username',$va['username'])->value('SUM(zjje)'):0;

		}

		$r = szt($m,$yhid);
		$z = Db::name('username')->where('id',$yhid)->find();
		$zjzje = Db::name('touzhu_list_ok')->where('username',$z['username'])->value('SUM(zjje)')?Db::name('touzhu_list_ok')->where('username',$z['username'])->value('SUM(zjje)'):0;
		$dlyj = Db::name('agent_balance')->where('agent',$z['username'])->value('SUM(balance)')?Db::name('agent_balance')->where('agent',$z['username'])->value('SUM(balance)'):'0';
		$this->assign('team',$r[1]);

		$r[1]['je'] += $z['je'];
		$r[1]['dlyj'] += $dlyj;
		$r[1]['dml'] += $z['dml'];
		$r[1]['zjzje'] += $zjzje;
		$r[1]['zcjje'] += $z['zcjje'];
		$r[1]['czzje'] += $z['czzje'];
		$r[1]['tzzje'] += $z['tzzje'];
		$r[1]['txzje'] += $z['txzje'];
		$this->assign('xiaoji',$r[1]);
		$this->assign('t',$r['0']);
		$this->assign('zjzje',$zjzje);
		$this->assign('dlyj',$dlyj);
		$this->assign('m',$z);
		return $this->fetch('cjgxt');
	}
	public function us_dlzy(){
		if(input('post.')){
			$id = input('uid');
			$tjr = input('xg_tjr') ? input('xg_tjr') : input('ytjr');
			$s = Db::name('username')->where('username',$tjr)->value('id');
			if(empty($s)){
			    js_tishi('推荐人不存在！', '/admin/Member/us_dlzy?uid='.$id);
			}
			$data=array('tjrid'=>$s,'tjr'=>$tjr,'zyh_tzzje'=>0);
			if(Db::name('username')->where('id',$id)->update($data)){
				js_tishi('更新成功', '/admin/Member/us_dllist');
			}else{
				alert_back('更新失败');
			}

		}else{
			$dl = Db::name('username')->where('id',input('uid'))->find();
			$dl_list = Db::name('username')->select();
			$this->assign('dllist',$dl_list);
			$this->assign('dl',$dl);
			return $this->fetch();
		}
	}
	public function us_select(){
		$dl_list = Db::name('username')->field('username')->select();
		return json($dl_list);
	}

	public function us_fp(){
	    $username = input('get.user');
	    $tjr = input('get.dl');
	    $s = Db::name('username')->where('username',$tjr)->value('id');
	    $data=array('tjrid'=>$s,'tjr'=>$tjr);
        if(Db::name('username')->where('username',$username)->update($data)){
        	$this->member_model->caozuorizhi_xieru('设置会员:'.input('get.user').'的上级代理商');
			js_tishi('更新成功', '/admin/Member/us_list');
		}else{
			alert_back('更新失败');
		}
	}

	public function dl_sh(){
		$a='';
		if(input('post.')){
			$wherea = array_filter(input('post.'));
			$where = array();
			foreach ($wherea as $k=>$v){
				if($k == 'ss_sql'){
					$a=$wherea[$k];
				}
				if($k == 'sDate1' || $k == 'sDate2'){
				    if(isset($wherea['sDate1']) && isset($wherea['sDate2']) && $wherea['sDate1'] != '' && $wherea['sDate2'] !=''){
						$star = strtotime($wherea['sDate1']." 00:00:00");
						$end = strtotime($wherea['sDate2']." 23:59:59");
						$where['a.reg_time']=['between',$star.','.$end];
					}else{
						alert_back('选择完整的时间！');
					}
				}
			}
		}

		//选择条件查询
		$us = input('param.us');
		if($us == 1){
			$where['a.bankname']=['>',0];
		}elseif($us == 2){
			$where['a.czzje']=['>',0];
		}elseif($us == 3){
			$where['a.txzje']=['>',0];
		}elseif($us == 4){
			$where['a.tzzje']=['>',0];
		}elseif($us == 5){
			$where['a.je']=['>',0];
		}elseif($us == 6){
			$where['a.open']=['>',0];
		}
		$where['a.swzh']=['<>','1'];
		
		$where['a.dlshstatus']=1;

		$query = Db::name('username')
				->alias('a')
				->field(['a.id as uid','a.username as username','a.je as je','a.open as open','a.reg_time as reg_time','a.fandian','a.login_time as login_time','a.login_ip as login_ip','a.czzje as czzje','a.txzje as txzje','a.tzzje as tzzje','a.tjr as tjr','a.beizhu as beizhu','a.nbzh as nbzh','a.reg_ip as reg_ip','a.bankname as bankname'])
				->join('__US_CLASS__ b','b.id=a.us_class')
				->field(['b.class_name as hy_name'])
				->where($where)
				->where('a.username|a.id|a.bankren|a.mobile','like','%'.$a.'%')
				->order('a.id desc')
				->paginate(16)
				->each(function($item, $key){
					    $item['dlfandian'] = Db::name('username')->where('username',$item['tjr'])->value('fandian');
					    return $item;
					});


		$this->assign('query',$query);
		return $this->fetch();
	}

	public function dlExamine(){
		$statu = input('statu');
		$uid = input('czid');

		$user = Db::name('username')->where('id',$uid)->find();
		$tj = Db::name('username')->where('tjm','<>','')->find();
		if($user['id']){
			if($statu=='2'){
				$tjm = $this->yztjm($tj,$this->code());
				$data=array('dlshstatus'=>$statu,'tjm'=>$tjm);

			}else{
				$data=array('dlshstatus'=>$statu);
			}
			if(Db::name('username')->where('id',$uid)->update($data)){
				$this->member_model->caozuorizhi_xieru('拒绝:'.$user['username'].'的返点申请');
				js_tishi('成功', 'dl_sh');
			}else{
				alert_back('失败');
			}
		}

	}
	public function dljieshou(){
		$id=input('uid');
		$fd = input('fd');
		$xz = input('xz');
		$statu=input('statu');
		$tj= Db::name('username')->where('tjm','<>','')->select();
		$user = Db::name('username')->where('id',$id)->find();
		$dl =  Db::name('username')->where('id',$user['tjrid'])->find();
		$tjm = $this->yztjm($tj,$this->code());

		$data=[];
		if(!$dl){$dl['fandian']='40';}
		if($xz==1){
			if($dl['fandian']<$fd){
				js_tishi('返点不能超过'.$dl['fandian'], 'dl_sh');
			}else{
				$data=array('fandian'=>$fd,'dlshstatus'=>$statu,'tjm'=>$tjm,'dl_time'=>time());

				if(Db::name('username')->where('id',$id)->update($data)){
					$this->member_model->caozuorizhi_xieru('审核通过:'.$user['username'].'的申请，返点:'.$fd);
						js_tishi('成功', 'dl_sh');
					}else{
						alert_back('失败');
					}
			}
		}else{
			$data=array('fandian'=>$fd,'dlshstatus'=>$statu,'tjm'=>$tjm,'tjr'=>'','tjrid'=>0,'dl_time'=>time());
			if(Db::name('username')->where('id',$id)->update($data)){
				$this->member_model->caozuorizhi_xieru('审核通过:'.$user['username'].'的申请，返点:'.$fd);
				js_tishi('成功', 'dl_sh');
			}else{
				alert_back('失败');
			}
		}

	}
	public function CheckedZhiUser(){
		$id = input('uid');
		$user = Db::name('username')->where('id',$id)->field('id,username,tjrid')->find();
		$dl = Db::name('username')->where('id',$user['tjrid'])->field('fandian')->find();
		$arr = $id.','.$user['username'].','.$dl['fandian'];
		echo $arr;
	}
	function yztjm($tj,$tjm){
		foreach ($tj as $v){
			if(strpos($v['tjm'],$tjm)==false){
				return $tjm;
			}else{
				$this->yztjm($tj,$this->code());
			}
		}
	}
	/**
	 * 代理审核开关
	 */
	public function agent_open_off(){
		if(input('post.')){
			$data['open'] = input('open');
			if(Db::name('agent_off')->where('id',1)->update($data)){
				if($data['open']==0){
					$this->member_model->caozuorizhi_xieru('将代理中心显示设置为:是');
				}
				if($data['open']==1){
					$this->member_model->caozuorizhi_xieru('将代理中心显示设置为:否');
				}
				js_tishi('更新成功', 'agent_open_off');
			}
		}else{
			$open = Db::name('agent_off')->where('id',1)->value('open');
			$this->assign('open',$open);
			return $this->fetch();
		}
	}
	public function voice(){

		$voice = Db::name("xt_tishi_msic")->where(['dl_open'=>1])->find();
		$this->assign('voice',$voice);
		$list = Db::name("xt_tishi_msic")->select();
		$this->assign('list',$list);
		if(input('post.')){
			$post = input('post.');
			$id = intval($post['voice']);
			Db::startTrans();
			try{
				Db::name('xt_tishi_msic')->where(['dl_open'=>1])->update(['dl_open'=>0]);
				$data = [
						'dl_open' => $post['dl_open'],
						'dl_class' => $post['dl_class']
				];
				Db::name("xt_tishi_msic")->where(['id'=>$id])->update($data);
				Db::commit();
				$this->member_model->caozuorizhi_xieru('修改了代理管理的声音提醒设置');
				alert_back("修改成功");
			}catch (Exception $e){
				Db::rollback();
				alert_back("修改失败：".$e->getMessage());
			}
		}
		return $this->fetch();
	}
	
	public function agentfandian(){
		$query = Db::name('agent_class')->where('status',1)->order('num','DESC')->select();
		$this->assign('query',$query);
		return $this->fetch();
	}
	public function agentAdd(){
		if(input('post.')){
			$data = input('post.');
			if(Db::name('agent_class')->data($data)->insert()){
				$this->member_model->caozuorizhi_xieru('新增代理返点');
				js_tishi('新增成功', 'agentfandian');
			}else{
				alert_back('错误');
			}	
		}else{
			return $this->fetch('agent_add');
		}
	}
	public function agentSet(){
		if(input('post.')){
			$data = input('post.');

			if(Db::name('agent_class')->update($data)){
				$this->member_model->caozuorizhi_xieru('修改了代理返点,ID:'.$data['id']);
				js_tishi('修改成功', 'agentfandian');
			}else{
				alert_back('未做修改');
			}
		}else{
			$uid = input('uid');
			$class = Db::name('agent_class')->where('id',$uid)->find();
			$this->assign('class',$class);
			$this->assign('uid',$uid);
			return $this->fetch('agent_set');
		}
	}
	public function agentDel(){
		$uid = input('uid');
		if(Db::name('agent_class')->where('id',$uid)->update(array('status'=>0))){
			$this->member_model->caozuorizhi_xieru('删除代理返点,ID:'.$uid);
			js_tishi('删除成功', 'agentfandian');
		}else{
			alert_back('失败');
		}
	}
	public function settingagent(){
		if(input('post.submit')){
			if(Db::name('xt_dl')->where('id',1)->update(array('content'=>input('post.content') ? input('post.content') : ''))){
				$this->member_model->caozuorizhi_xieru('更新代理简介');
				js_tishi('更新成功', 'settingagent');
			}else{
				alert_back('更新失败');
			}	
		}else{
			$query = Db::name('xt_dl')->where('id',1)->find();
			$this->assign('query',$query['content']);
			return $this->fetch();
		}
	}

}